using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure;
using ProduceBasicData.Infrastructure.Interface;

public class DeleteStockInOrderHandler : IRequestHandler<DeleteStockInOrderCommand, ApiResult<int>>
{
    private readonly IBaseRespository<StockInOrder> _stockInOrderRepository;
    private readonly IBaseRespository<StockInOrderItem> _stockInOrderItemRepository;
    private readonly MyDBContext _myDBContext;

    public DeleteStockInOrderHandler(
        IBaseRespository<StockInOrder> stockInOrderRepository,
        IBaseRespository<StockInOrderItem> stockInOrderItemRepository,
        MyDBContext myDBContext)
    {
        _stockInOrderRepository = stockInOrderRepository;
        _stockInOrderItemRepository = stockInOrderItemRepository;
        _myDBContext = myDBContext;
    }

    public async Task<ApiResult<int>> Handle(DeleteStockInOrderCommand request, CancellationToken cancellationToken)
    {
        try
        {
            var stockInOrder = await _stockInOrderRepository.GetModelAsync(request.Id);
            if (stockInOrder == null)
            {
                return new ApiResult<int>
                {
                    Msg = "未找到指定的入库单",
                    Code = ApiEnum.Failed
                };
            }

            using var transaction = await _myDBContext.Database.BeginTransactionAsync(cancellationToken);
            try
            {
                stockInOrder.Isdel = true;
                await _stockInOrderRepository.Update(stockInOrder); 

                var items = await _stockInOrderItemRepository.GetAllAsync(
                    i => i.StockInOrderId == request.Id && !i.Isdel
                );

                if (items != null && items.Any())
                {
                    foreach (var item in items)
                    {
                        item.Isdel = true;
                        await _stockInOrderItemRepository.Update(item); 
                    }
                }

                await _myDBContext.SaveChangesAsync(cancellationToken);
                await transaction.CommitAsync(cancellationToken);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = stockInOrder.Id
                };
            }
            catch (Exception)
            {
                await transaction.RollbackAsync(cancellationToken);
                throw;
            }
        }
        catch (Exception ex)
        {
            return new ApiResult<int>
            {
                Code = ApiEnum.Failed,
                Msg = $"删除入库单时发生错误: {ex.Message}"
            };
        }
    }
}